package net.sureon.common;

import java.io.UnsupportedEncodingException;
import java.util.Locale;

import net.sureon.app.AppContext;
import net.sureon.common.exception.ExceptionUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.MessageResources;

/**
 * I18Nsupport helper class, which is to return i18N messages based on the
 * passed locale and exception key.
 * 
 * @author jason
 * 
 */
public class I18nSupport {
	public static Locale defaultLocale = Locale.SIMPLIFIED_CHINESE;
	private static final Log logger = LogFactory.getLog(I18nSupport.class);
	/**
	 * Loading message files from resources dir. The files loaded are: 1)
	 * sureon_locale.properties, and sureon.properties if no locale specific
	 * message found.
	 */
	private static MessageResources messages = MessageResources
			.getMessageResources("resources.sureon");

	public static String getMessage(String key) {
		return getMessage(key, null, null);
	}

	public static String getMessage(String key, Object[] args) {
		return getMessage(key, args, null);
	}

	public static String getMessage(String key, Object[] args, Locale locale) {
		if (locale == null) {
			locale = AppContext.getLocale();
		}
		String theReturn = messages.getMessage(locale, key, args);
		if (theReturn == null) {
			theReturn = key + " - untranslated.";
		} else {
			try {
				theReturn = new String(theReturn.getBytes("ISO8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("convert msg string met exception", e);
			}
		}
		return theReturn;
	}
}
